package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.example.demo.entity.ADVideoEntity;
import com.example.demo.entity.MsgEntity;
import com.example.demo.entity.PostJsonEntity;
import com.example.demo.service.HelloService;
import javafx.geometry.Pos;
import mode.ClientBackData;
import mode.helloview;
import org.attoparser.util.TextUtil;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.TextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;


@RestController
public class HelloDemo {

    private final HelloService helloService;

    public HelloDemo(HelloService helloService) {
        this.helloService = helloService;
    }

    //阻塞队列    有长度的队列
    private ArrayBlockingQueue<PostJsonEntity<Object>> array = new ArrayBlockingQueue<PostJsonEntity<Object>>(50);
    private ArrayList<ClientBackData> postJsonEntityArrayList = new ArrayList<>();

    @RequestMapping("/nextIndex")
    public String switchIndex() {
        PostJsonEntity<Object> jsonEntity = array.poll();
        return "====>" + String.valueOf(jsonEntity == null ? "null" : jsonEntity.toString());
    }

    @RequestMapping("/clearQueue")
    public String clearQueue() {
        array.clear();
        return "clear";
    }
    @RequestMapping("/clearResult")
    public String clearResultQueue() {
        postJsonEntityArrayList.clear();
        return "clear";
    }



    @RequestMapping("/callBackData")
    public List<ClientBackData> callBackData(){
        System.out.println("=====callBackData==>"+postJsonEntityArrayList.size());
        if (postJsonEntityArrayList.size()>=50){
            postJsonEntityArrayList.remove(postJsonEntityArrayList.size()-1);
        }
        return postJsonEntityArrayList;
    }



    @RequestMapping(value = "/commitCommand", method = RequestMethod.POST)
    public String commitCommand(@RequestParam("command") String command, @RequestParam("statue") String statue, @RequestParam("data") String data) {
        System.out.println(String.format("=command:%s====statue:%s====data:%s=======>", command, statue, data));
        boolean isSuccess = false;
        if (command != null && command.length() != 0) {
            PostJsonEntity<Object> postJsonEntity = new PostJsonEntity<>();
            postJsonEntity.setData(JSON.parse(data));
            postJsonEntity.setStatus(statue);
            postJsonEntity.setCommand(command);
            postJsonEntity.setCommandNumber(String.valueOf(new Random(System.currentTimeMillis()).nextInt()));

            try {
                isSuccess = array.offer(postJsonEntity, 3, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
                isSuccess = false;
            }
        }

        return command + "===>" + isSuccess;
    }

    @RequestMapping("/addDB")
    public String addDB() {
        helloview sqlEntity = new helloview();
        sqlEntity.setId(new Random(System.currentTimeMillis()).nextInt());
        sqlEntity.setCommand("10010");
        sqlEntity.setData(UUID.randomUUID().toString());
        sqlEntity.setTime(String.valueOf(System.currentTimeMillis()));
        System.out.println("====sqlEntity=>" + sqlEntity.toString());
        helloService.insert(sqlEntity);

        return UUID.randomUUID().toString();
    }


    @RequestMapping(value = "/api/robot/postInFaceMsg", method = RequestMethod.POST)
    public String postFace(@RequestParam("faceValue") String faceValue, @RequestParam("enterTime") String enterTime, @RequestParam("robotID") String robotID,
                           @RequestParam("carNum") String carNum, @RequestParam("enterPic") String enterPic) {
        System.out.println(String.format("faceValue:%s==enterTime:%s=robotID:%s=carNum:%s=enterPic:%s>>>>>>", faceValue, enterTime, robotID, carNum, enterPic));
        return "-------";
    }

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String index(@RequestBody String params) {
        System.out.println("hello==code:%s=status:%s=command:%s=data:%s>>>>>>" + params);
      /*  PostJsonEntity<String>  firstResult = array.peek();
        boolean isEmpty = null != firstResult;
        if (isEmpty){
            if ("0".equals(code)){
               // array.poll();

            }
        }*/

        ClientBackData clientBackData =  JSON.parseObject(params, ClientBackData.class);
        postJsonEntityArrayList.add(clientBackData);
        if (clientBackData.getCode() == 0){
            array.poll();
        }else {
            array.poll();
        }
        return "";
    }


    @RequestMapping(value = "/postArgument", method = RequestMethod.POST)
    public String getArgument(@RequestParam("command") String command,
                              @RequestParam("data") String data,
                              @RequestParam("commantNum") String commandNum) {
        PostJsonEntity<Object> postJsonEntity = new PostJsonEntity<>();
        postJsonEntity.setCommand(command);
        postJsonEntity.setCommandNumber(commandNum);
        postJsonEntity.setStatus("1");
        postJsonEntity.setData(data);
        boolean isSuccess = false;
        try {
            isSuccess = array.offer(postJsonEntity, 3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "=====add=Success::>" + isSuccess;
    }

    @RequestMapping(value = "/post/hello", method = RequestMethod.POST)
    public PostJsonEntity postIndex(@RequestParam("mac") String mac,
                                    @RequestParam("time") String time,
                                    @RequestParam("ip") String ip,
                                    @RequestParam("port") String port,
                                    @RequestParam("type") String type,
                                    @RequestParam("sn") String sn,
                                    @RequestParam("deviceName") String deviceName,
                                    @RequestParam("deviceId") String deviceId,
                                    @RequestParam("siteId") String siteId,
                                    @RequestParam("siteName") String siteName,
                                    @RequestParam("divisionId") String divisionId) {
        System.out.println(String.format("postIndex=mac:%s=time:%s=ip:%s=port:%s=type:%s=sn:%s=deviceName:%s=========>", mac, time, ip, port, type, sn, deviceName));
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.setGate_control("sdfsfsfsdfs");

        ADVideoEntity adVideoEntity = new ADVideoEntity();
        adVideoEntity.setIsOpen("true");
        adVideoEntity.setVideo1("https://static.yximgs.com/s1/videos/home-2.mp4");
/*
        PostJsonEntity<MsgEntity> postJsonEntity = new PostJsonEntity<>();
        postJsonEntity.setCommand("20105");
        postJsonEntity.setStatus("1");
        postJsonEntity.setCommandNumber("11");
        postJsonEntity.setData(msgEntity);
*/

        PostJsonEntity<Object> postJsonEntity = array.peek();
        System.out.println(array.size() + "=========postJsonEntity===>" + (postJsonEntity != null ? postJsonEntity.toString() : "Null"));
        return /*array.poll() == null?new PostJsonEntity():*/postJsonEntity;
    }
    //实现Spring Boot 的文件下载功能，映射网址为/download
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) throws UnsupportedEncodingException {

        // 获取指定目录下的第一个文件
        File scFileDir = new File("C://Users//64460//Pictures//test");
        File TrxFiles[] = scFileDir.listFiles();
        System.out.println(TrxFiles[0]);
        String fileName = TrxFiles[0].getName(); //下载的文件名

        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "C://Users//64460//Pictures//test";
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download the song successfully!");
                }
                catch (Exception e) {
                    System.out.println("Download the song failed!");
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}
